package com.lad.transactional_propagation.annotation.aspect;

import com.lad.transactional_propagation.config.TransactionConfig;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;

@Component
@Aspect
public class TransactionAspect {
    @Autowired
    private TransactionConfig transactionConfig;//事务管理



    @Pointcut("@annotation(com.lad.transactional_propagation.annotation.MyTransaction)")
    public void myTransaction() {
    }

    @Around("myTransaction()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) {
        TransactionStatus begin = null;
        try {
            //手动开启事务
            begin = transactionConfig.begin();
            System.out.println(">>>>>>>>>>>事务开启<<<<<<<<<<");

            Object result = proceedingJoinPoint.proceed();
            //手动提交事务
            transactionConfig.commit(begin);
            System.out.println(">>>>>>>>>>>事务提交<<<<<<<<<<");
            return result;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            //手动回滚事务
            if (begin != null) {
                transactionConfig.rollback(begin);
            }
            System.out.println(">>>>>>>>>>>事务回滚<<<<<<<<<<");
        }
        return null;
    }
}